package com.geek.jdbc;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import java.sql.*;

public class JdbcUtil {

    public static final String url = "jdbc:mysql://10.70.25.129:3306/mall_master?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&&rewriteBatchedStatements=true&serverTimezone=GMT%2B8";

    public static final String username = "root";

    public static final String password = "devops20181206";

    /**
     *  批量 + 事务
     *  如果改为MyISAM 引擎效果应该会好点
     *  耗时26s
     * @param args
     */
    public static void main(String[] args) {
        Snowflake snowflake = IdUtil.createSnowflake(1, 1);

        Connection conn = null;
        PreparedStatement pstmt = null;
        long start = System.currentTimeMillis();
        try {
            String sql = "insert into orders (order_id,notes) values(?,?)";
            conn = DriverManager.getConnection(url,username,password);
            conn.setAutoCommit(false);
            pstmt = conn.prepareStatement(sql);
            for (int i = 0; i < 1000000; i++) {
                pstmt.setLong(1, snowflake.nextId());
                pstmt.setString(2, "订单");
                pstmt.addBatch();
            }
            pstmt.executeBatch();
            conn.commit();
            conn.setAutoCommit(true);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (pstmt != null) {
                try {
                    pstmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            long end = System.currentTimeMillis();
            System.out.println("耗时：" + (end - start) / 1000 + "s");
        }
    }

}
